package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"product/goodsrpc/goodsrpc"
	"product/goodsrpc/internal/svc"
	"product/model/mysql"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateGoodsLogic {
	return &UpdateGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateGoodsLogic) UpdateGoods(in *goodsrpc.UpdateGoodsRequest) (*goodsrpc.UpdateGoodsResponse, error) {
	// todo: add your logic here and delete this line

	var findgoods mysql.Good
	mysql.DB.Where("id=?", in.Id).Find(&findgoods)
	if findgoods.ID == 0 {
		return nil, fmt.Errorf("当前商品不存在")
	}
	if findgoods.UserId != int(in.Userid) {
		return nil, fmt.Errorf("当前商品不是该用户购买的")
	}

	good := mysql.Good{
		Model: gorm.Model{ID: uint(in.Id)},
		Num:   int(in.Num),
		Price: int(in.Price),
	}
	mysql.DB.Updates(&good)
	return &goodsrpc.UpdateGoodsResponse{Id: int64(good.ID)}, nil
}
